#
# Unit Allegiance Mod
# CvViSaEventManager
# 
from CvPythonExtensions import *
import CvUtil

import CvEventManager
import Popup as PyPopup
import PyHelpers
import CvConfigParser
import sys


gc = CyGlobalContext()

PyPlayer = PyHelpers.PyPlayer
PyGame = PyHelpers.PyGame()
PyInfo = PyHelpers.PyInfo

def loadConfigurationData():

	global g_WinnerCombatTypeFilterList
	global g_LoserCombatTypeFilterList
	global g_iUnitAllegianceChangeChance
	global g_iDamageAfterAllegianceChange
	global g_NoAnimalAllegiance

#	UNITCOMBAT_HELICOPTER = gc.getInfoTypeForString("UNITCOMBAT_HELICOPTER")
#       UNITCOMBAT_SIEGE = gc.getInfoTypeForString("UNITCOMBAT_SIEGE")
#       UNITCOMBAT_ARMOR = gc.getInfoTypeForString("UNITCOMBAT_ARMOR")
#       UNITCOMBAT_NAVAL = gc.getInfoTypeForString("UNITCOMBAT_NAVAL")

        # Change the value to include the unit combat types of units belonging to the 
        # winner of combat that should not be allowed to influence the change of 
        # allegiance of enemy units.
        # Default value is UNITCOMBAT_HELICOPTER
#        g_WinnerCombatTypeFilterList = [UNITCOMBAT_HELICOPTER]

        # Change the value to include the unit combat types of units belonging to the 
        # loser of combat that should not be allowed to change their allegiance.
        # Default value is UNITCOMBAT_SIEGE, UNITCOMBAT_ARMOR, UNITCOMBAT_HELICOPTER, UNITCOMBAT_NAVAL
#        g_LoserCombatTypeFilterList = [UNITCOMBAT_SIEGE, UNITCOMBAT_ARMOR, UNITCOMBAT_HELICOPTER, UNITCOMBAT_NAVAL]

	# Increase or decrease the value to change the chance that units will change 
	# their allegiance before being defeated in combat
	# Default value is 5
	g_iUnitAllegianceChangeChance = 5

	# Increase or decrease the value to change the amount of damage units will have
	# after they change their allegiance.
	# Default value is 50
	g_iDamageAfterAllegianceChange = 50

	# set this to true if you don't want animals to change allegiance
	g_NoAnimalAllegiance = False
		
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
#		tmpWinnerCombatTypeFilterList = config.get("Unit Allegiance Mod", "Winner Combat Type Filter", "UNITCOMBAT_HELICOPTER")
#		tmpLoserCombatTypeFilterList = config.get("Unit Allegiance Mod", "Loser Combat Type Filter", "UNITCOMBAT_SIEGE, UNITCOMBAT_ARMOR, UNITCOMBAT_HELICOPTER, UNITCOMBAT_NAVAL")
		g_iUnitAllegianceChangeChance = config.getint("Unit Allegiance Mod", "Unit Allegiance Change Chance", 5)
		g_iDamageAfterAllegianceChange = config.getint("Unit Allegiance Mod", "Damage After Allegiance Change", 50)
		g_NoAnimalAllegiance = config.getboolean("Unit Allegiance Mod", "No Animal Allegiance", False)
	
		
#	if(len(tmpWinnerCombatTypeFilterList) > 0):
#		tmpWinnerCombatTypeFilterList = tmpWinnerCombatTypeFilterList.split(", ")
		
#		g_WinnerCombatTypeFilterList = []
		
#		for combatType in tmpWinnerCombatTypeFilterList:
#			g_WinnerCombatTypeFilterList.append(gc.getInfoTypeForString(combatType))


#	if(len(tmpLoserCombatTypeFilterList) > 0):
#		tmpLoserCombatTypeFilterList = tmpLoserCombatTypeFilterList.split(", ")
		
#		g_LoserCombatTypeFilterList = []
		
#		for combatType in tmpLoserCombatTypeFilterList:
#			g_LoserCombatTypeFilterList.append(gc.getInfoTypeForString(combatType))
	
	
# globals
###################################################
class CvUnitAllegianceEventManager:
	def __init__(self, eventManager):

		eventManager.addEventHandler("combatResult", self.onCombatResult)
		eventManager.addEventHandler("windowActivation", self.onWindowActivation)
		loadConfigurationData()
		
		
	def onWindowActivation(self, argsList):
		'Called when the game window activates or deactivates'
		bActive = argsList[0]

		if(bActive):
			loadConfigurationData()
			
			
	def onCombatResult(self, argsList):
		'Combat Result'

		pWinner,pLoser = argsList

		self.handleCombatResult(pWinner, pLoser)

	
	# Performs the appropriate unit allegience change if necessary.
	def handleCombatResult(self, objWinnerUnit, objLoserUnit):
		
		loserCombatType = objLoserUnit.getUnitCombatType()
		winnerCombatType = objWinnerUnit.getUnitCombatType()
		
		objWinnerPlayer = gc.getPlayer(objWinnerUnit.getOwner())
		
		# Return if the losers combat type is in the losers filter list
#		if(loserCombatType in g_LoserCombatTypeFilterList):
#			return

		# Return if the winners combat type is in the winners filter list
#		if(winnerCombatType in g_WinnerCombatTypeFilterList):
#			return

		# Return if animals should not be captured
		if ( objLoserUnit.isAnimal() ):
			if ( g_NoAnimalAllegiance ):
				return
		
		# Get a random number between 1 and 100
		iRand = CyGame().getSorenRandNum(100, "Random Unit Allegience Number.")
		
		#Return if the random number is greater than the configured value
		if(iRand > g_iUnitAllegianceChangeChance):
			return
			
		# Create the new instance of the unit	
		objNewUnit = objWinnerPlayer.initUnit(objLoserUnit.getUnitType(),  objWinnerUnit.getX(), objWinnerUnit.getY(), UnitAITypes.NO_UNITAI)
		
		# Finish off the units moves
		objNewUnit.finishMoves()
		objNewUnit.setDamage(g_iDamageAfterAllegianceChange, False)
		objNewUnit.setExperience(objLoserUnit.getExperience(), -1)
		objNewUnit.setLevel(objLoserUnit.getLevel())

		# Go through all of the promotions in the game	
		for iPromotion in range(gc.getNumPromotionInfos()):
			
			# If the losing unit has the current promotion, give it to the new 
			# unit
			if (objLoserUnit.isHasPromotion(iPromotion)):
				objNewUnit.setHasPromotion(iPromotion, True)			
		
		return
		
